package com.shundr.order;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
import com.shundr.R;
import com.shundr.base.BaseActivity;
import com.shundr.cargo.http.CargoRequest;
import com.shundr.common.util.ProgressDialogHelper;
import com.shundr.common.util.ToastHelper;
import com.shundr.common.view.CListView;
import com.shundr.common.view.CListView.OnLoadMoreListener;
import com.shundr.common.view.CListView.OnRefreshListener;
import com.shundr.common.view.DialogDelete;
import com.shundr.common.view.DialogDelete.onDeleteListener;
import com.shundr.frame.constant.LContext;
import com.shundr.frame.http.LHttpRequest;
import com.shundr.order.adapter.OrderItemAdapter;
import com.shundr.order.http.OrderRequest;
import com.shundr.order.model.CargoOrderInfo;

/**
 * 订单列表
 * OrderListActivity
 * 
 * @author larry 2015-5-16 下午2:15:38 
 * @version 1.0.0
 *
 */
public class OrderListActivity extends BaseActivity {

	private CListView mListView;
	private RelativeLayout mLayoutNoContent;
	private TextView tvNoContent;
	
	private static final int PAGE_SIZE = LContext.PAGE_SIZE;
	private int pageNo = 0;
	
	private String mStatus = CargoOrderInfo.OrderStatus.ALL + "";
	
	private OrderItemAdapter mAdapter;
	
	private List<CargoOrderInfo> mList = new ArrayList<CargoOrderInfo>();
	
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			try {
				switch (msg.what) {
				case CargoRequest.GET_CARGO_LIST_SUCCESSED:
					@SuppressWarnings("unchecked")
					List<CargoOrderInfo> infos = (List<CargoOrderInfo>)msg.obj;
					if (infos != null) {
						if (infos.size() > 0) {
							if (pageNo == 0) {
								mList.clear();
								mListView.setVisibility(View.VISIBLE);
								mLayoutNoContent.setVisibility(View.GONE);
								if (infos.size() >= PAGE_SIZE) {
									mListView.setCanLoadMore(true);
									mListView.setAutoLoadMore(true);
									mListView.setCanRefresh(true);
								} else {
									mListView.setCanLoadMore(false);
									mListView.setAutoLoadMore(false);
									mListView.setCanRefresh(false);
								}
							}
							mList.addAll(infos);
							mAdapter.notifyDataSetChanged();
							if (pageNo == 0) {
								mListView.setSelection(0);
							}
							pageNo = pageNo + 1;
						} else {
							if (pageNo == 0) {
								mListView.setVisibility(View.GONE);
								mLayoutNoContent.setVisibility(View.VISIBLE);
							} else {
								ToastHelper.toastLong(mContext, "最后一页");
							}
						}
					}
					ProgressDialogHelper.dismiss();
					mListView.onRefreshComplete();
					mListView.onLoadMoreComplete();
					break;
				case LHttpRequest.REQUEST_FAILED:
					ProgressDialogHelper.dismiss();
					mListView.onLoadMoreComplete();
					mListView.onRefreshComplete();
					ToastHelper.toastShort(mContext, msg.obj.toString());
					break;

				default:
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			super.handleMessage(msg);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
		 // 生成一个SpinnerAdapter
		SpinnerAdapter adapter = ArrayAdapter.createFromResource(this,
				R.array.order_status,
				R.layout.item_actionbar_spinner);
        // 为ActionBar设置下拉菜单和监听器
        mActionBar.setListNavigationCallbacks(adapter, new DropDownListenser());
        
		setContentView(R.layout.activity_order_list);
		mListView = (CListView) findViewById(R.id.lv_list);
		mLayoutNoContent = (RelativeLayout)findViewById(R.id.layout_no_content);
		tvNoContent = (TextView)findViewById(R.id.tv_no_content);
		tvNoContent.setText("您还没有订单");
		mAdapter = new OrderItemAdapter(mList, mContext);
		mListView.setAdapter(mAdapter);
		mListView.setCanLoadMore(false);
		mListView.setAutoLoadMore(false);
		mListView.setCanRefresh(true);
		mListView.setOnRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				pageNo = 0;
				new OrderRequest(mContext, mHandler).getOrderLsit(PAGE_SIZE, mStatus, pageNo * PAGE_SIZE);
			}
		});
		mListView.setOnLoadListener(new OnLoadMoreListener() {
			@Override
			public void onLoadMore() {
				new OrderRequest(mContext, mHandler).getOrderLsit(PAGE_SIZE, mStatus, pageNo * PAGE_SIZE);
			}
		});
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				try {
					String orderId = mList.get(position-1).getOrderId()+"";
					Intent intent=new Intent(mContext, OrderDetailsActivity.class);
					intent.putExtra("orderId", orderId);
					startActivityForResult(intent, 500);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		
		mListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					final int position, long id) {
				CargoOrderInfo info = mList.get(position - 1);
				if(info!=null){
					final String orderId=info.getOrderId() + ""; 
					DialogDelete dialogDelete=new DialogDelete(mContext);
					dialogDelete.setOnDeleteListener(new onDeleteListener() {
						
						@Override
						public void delete() {
							new OrderRequest(mContext, new Handler(){

								@Override
								public void handleMessage(Message msg) {
									super.handleMessage(msg);
									switch (msg.what) {
									case OrderRequest.UPDATE_ORDER_SUCCESSED:
										ToastHelper.toastShort(mContext, "删除成功");
										mList.remove(position-1);
										mAdapter.notifyDataSetChanged();
										if(mList.size() == 0){
											mListView.setVisibility(View.GONE);
											mLayoutNoContent.setVisibility(View.VISIBLE);
										}
										break;
									case LHttpRequest.REQUEST_FAILED:
						                ToastHelper.toastShort(mContext, msg.obj.toString());
										break;
									default:
										break;
									}
								}
								
							}).updateOrderStatus(orderId, 9);//9是关闭(隐藏)订单
						}
					});
					dialogDelete.show();
				}
				return true;
			}
		});
	}
	
	/**
	 * 实现 ActionBar.OnNavigationListener接口
	 */
	class DropDownListenser implements OnNavigationListener {
		// 得到和SpinnerAdapter里一致的字符数组
		String[] listNames = getResources()
				.getStringArray(R.array.order_status);

		/* 当选择下拉菜单项的时候，将Activity中的内容置换为对应的Fragment */
		public boolean onNavigationItemSelected(int itemPosition, long itemId) {
			switch (itemPosition) {
			case 0:
				mStatus=CargoOrderInfo.OrderStatus.ALL + "";
				break;
			case 1:
				mStatus=CargoOrderInfo.OrderStatus.WAIT_ME_HANDLE + "";
				break;
			case 2:
				mStatus=CargoOrderInfo.OrderStatus.WAIT_OTHER_HANDLE + "";
				break;
			case 3:
				mStatus=CargoOrderInfo.OrderStatus.COMPLETED + "";
				break;
			case 4:
				mStatus=CargoOrderInfo.OrderStatus.INVALIDATED + "";
				break;
			default:
				break;
			}
			onRefesh();
			return true;
		}
	}
	
	public void onRefesh(){
//		if(mStatus == status)
//			return;
		ProgressDialogHelper.show(mContext, "数据加载中,请稍后...");
		pageNo = 0;
		new OrderRequest(mContext, mHandler).getOrderLsit(PAGE_SIZE, mStatus, pageNo * PAGE_SIZE);
	}

	public void onChanged(String status){
//		if(mStatus == status)
//			return;
		mStatus = status;
		pageNo = 0;
		new OrderRequest(mContext, mHandler).getOrderLsit(PAGE_SIZE, mStatus, pageNo * PAGE_SIZE);
	}


	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == 501) {
			onRefesh();
		}
	}

}
